/*
 *
 *  Copyright (C) 2009 UMA
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *
 *  Author : Juan Pablo Mar�n Tobar <jpablomt@uma.es>
 *
 *  Version: 1.0
 */

package com.LibreGeoSocial.App.Perfil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.ListIterator;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.LibreGeoSocial.Api.LibreGeoSocial;
import com.LibreGeoSocial.App.R;

public class ProfileInformation extends Activity {
	
	/* TAG for log messages */
	private static final String TAG = "tag_profile";
	
	/* Constants for parsers */
	public static final int OK = 200;
	public static final int ERROR = 500;
	public static final String DESCRIPTION = "description";
	public static final String PROPOSAL = "proposal";
	public static final String TEXT = "text";
	public static final String TOPIC = "topic";
	public static final String IDENTIFIER = "identifier";
	public static final String QDESCRIPTOR = "qdescriptor";
	public static final String STATUS = "status";
	public static final String QUESTION = "question";
	public static final String SINGLE = "single";
	public static final String MULTIPLE = "multiple";
	public static final String RESPONSE = "response";
	public static final String TYPE = "type";
	public static final String CODE = "code";
	public static final String MESSAGE = "message";
	public static final String RESULT = "result";
	public static final String OPERATION = "operation";
	public static final String ANSWER = "answer";
	public static final String LGS = "libregeosocial";
	
		
	
	/* local variables */
	private Question question;
	private Response response;
	
	// String information
	private String strErrorServer = "There aren't further questions at the server";
	// String more questions
	private String strMoreQuestion = "Further complete the profile?";
	//String for errors 
	private String errorServer = "Access error to questions server";
	
	/* String buttons */
	private String send = "Send";
	private String cancel = "Cancel";
	
	/* EditText for comments */
	private EditText comment;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initialize();
    }
    
    private void initialize(){
    	question = LibreGeoSocial.getInstance().getQuestion();
    	if (question.getStatus()!=Question.INITIAL) showQuestion();
    	else defaultLayout();
    }
    
    private void showQuestion(){
    	switch (question.getStatus()){
    	case Question.RIGTH:
    		response = new Response();
        	response.setQuestion_id(question.getIdentifier());
        	ScrollView sc = new ScrollView(this);
        	sc.setFillViewport(true);
	        LinearLayout ll;
	        if (question.getType().equals(SINGLE)){
	        	ll = showExclusiveQuestion();
	        }else {
	        	ll = showMultipleQuestion();
	        }
	        
	        ll.setBackgroundResource(R.drawable.label_back);
	        // add layout coments
	        ll.addView(setLayoutComment());
	        //add options buttons [send, cancel]
	        addButtonLayout(ll);
	        sc.addView(ll);
	        this.setContentView(sc);
    		break;
    	case Question.ERROR:
    		new AlertDialog.Builder(this)
            .setMessage(question.getErrorDescription())
            .setCancelable(false)
            .setPositiveButton("Accept", new DialogInterface.OnClickListener() {
            	public void onClick(DialogInterface dialog, int id) {
            		defaultLayout();
            	}
            })
            .show();
    		break;
    	default:
    		new AlertDialog.Builder(this)
            .setMessage(errorServer)
            .setCancelable(false)
            .setPositiveButton("Accept", new DialogInterface.OnClickListener() {
            	public void onClick(DialogInterface dialog, int id) {
                    defaultLayout();
            	}
            })
            .show();
    		break;
    	}
    }
    
    /*
     * Default view
     * */
    private void defaultLayout(){
       	LinearLayout ll = new LinearLayout(this);
       	ll.setOrientation(LinearLayout.VERTICAL);
       	ll.setBackgroundResource(R.drawable.label_back);
       	TextView tv = new TextView(this);
       	tv.setTextSize(15);
       	tv.setTypeface(Typeface.DEFAULT_BOLD);
    	tv.setTextColor(Color.BLACK);
       	switch(question.getStatus()){
       	case Question.ERROR://no more questions
    	        tv.setText(strErrorServer);
    	        tv.setPadding(5,20,0,0);
    	        ll.addView(tv);
       		break;
       	case Question.RIGTH:
       		tv.setText(strMoreQuestion);
       		tv.setPadding(60,20,0,30);
       		ll.addView(tv);
       		LinearLayout layer_boton=new LinearLayout(this);
       		layer_boton.setLayoutParams(new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
       		layer_boton.bringToFront();
       		Button ba = new Button(this);
               ba.setWidth(107);
               ba.setHeight(36);
               ba.setTypeface(Typeface.DEFAULT_BOLD);
               ba.setText("Yes");
               layer_boton.addView(ba);
               layer_boton.setGravity(Gravity.CENTER_HORIZONTAL);
               ll.addView(layer_boton);
               ba.setOnClickListener(
               		new OnClickListener() {    
               				public void onClick(View v) {
               					initialize();
               				}
               		}
               );
       		break;
       	case Question.INITIAL:
       		tv.setText(strMoreQuestion);
       		tv.setPadding(60,20,0,30);
       		ll.addView(tv);
       		LinearLayout layer_boton2=new LinearLayout(this);
       		layer_boton2.setLayoutParams(new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
       		layer_boton2.bringToFront();
       		Button bc = new Button(this);
       		bc.setWidth(107);
            bc.setHeight(36);
            bc.setTypeface(Typeface.DEFAULT_BOLD);
            bc.setText("Yes");
            layer_boton2.addView(bc);
            layer_boton2.setGravity(Gravity.CENTER_HORIZONTAL);
            ll.addView(layer_boton2);
               bc.setOnClickListener(
               		new OnClickListener() {    
               				public void onClick(View v) {
               					initialize();
               				}
               		}
               );
       		break;
       	}
    	setContentView(ll);
    }
    
    public LinearLayout setLayoutComment(){
    	LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        TextView tv = new TextView(this);
        tv.setTextColor(Color.BLACK);
        tv.setTextSize(15);
	    tv.setTypeface(Typeface.DEFAULT_BOLD);
        tv.setText("Comment");
        ll.addView(tv);
        comment = new EditText(this);
        comment.setTextColor(Color.BLACK);
        comment.setTextSize(15);
        comment.setTypeface(Typeface.DEFAULT_BOLD);
        ll.addView(comment);
        return ll;
    }
    
    private void addButtonLayout(LinearLayout ll){
        LinearLayout lh = new LinearLayout(this);
        lh.setOrientation(LinearLayout.HORIZONTAL);
        lh.bringToFront();
        Button ba = new Button(this);
        ba.setWidth(107);
        ba.setHeight(36);
        ba.setTypeface(Typeface.DEFAULT_BOLD);
        ba.setText(send);
        lh.addView(ba);
        TextView espacio=new TextView(this);
        espacio.setText(" ");
        espacio.bringToFront();
        lh.addView(espacio);
        Button bc = new Button(this);
        bc.setWidth(107);
        bc.setHeight(36);
        bc.setTypeface(Typeface.DEFAULT_BOLD);
        bc.setText(cancel);
        lh.addView(bc);
        ll.addView(lh);

        ba.setOnClickListener(
        		new OnClickListener() {    
        				public void onClick(View v) {
        					//send answer
        					//showResponse();
        					sendResponse();
        				}
        		}
        );
        
        bc.setOnClickListener(
        		new OnClickListener() {    
        				public void onClick(View v) {
        			        // cancel answer
        					defaultLayout();
        				}
        		}
        );
    }
    
    public LinearLayout showExclusiveQuestion(){
        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);

        TextView tv = new TextView(this);
        tv.setTextColor(Color.BLACK);
        tv.setTextSize(15);
	    tv.setTypeface(Typeface.DEFAULT_BOLD);
        tv.setText(question.getText());
        ll.addView(tv);
        
        RadioGroup buttonGroup =  new RadioGroup(this);
        buttonGroup.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
         RadioGroup.LayoutParams rlp = new RadioGroup.LayoutParams(
                RadioGroup.LayoutParams.WRAP_CONTENT,
                RadioGroup.LayoutParams.WRAP_CONTENT);
        ll.addView(buttonGroup);
        // add buttons answers
        ArrayList<Answer> listAnswer = question.getList_answer();
        ListIterator<Answer> li = listAnswer.listIterator();
        while (li.hasNext()){
            RadioButton cb = new RadioButton(this);
            cb.setHighlightColor(0xff3366ff);
            cb.setLinkTextColor(0xff3366ff);
            Answer answer = li.next();
            final int code = answer.getCode();
            cb.setTextSize(15);
    	    cb.setTypeface(Typeface.DEFAULT_BOLD);
            cb.setText(answer.getText());
            
            cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
    			public void onCheckedChanged(CompoundButton buttonView,
    					boolean isChecked) {
    				if(isChecked){
    					response.setAnswer(code);
    				} else {
    					response.deleteAnswer(code);
    				}
    			}
    		});
            cb.setLayoutParams(rlp);
            buttonGroup.addView(cb);                  
        }
        return ll;
    }
    
    public LinearLayout showMultipleQuestion(){
    	LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        TextView tv = new TextView(this);
        tv.setTextColor(Color.BLACK);
        tv.setTextSize(15);
	    tv.setTypeface(Typeface.DEFAULT_BOLD);
        tv.setText(question.getText());
        ll.addView(tv);
           
        // add buttons answers
        ListIterator<Answer> li = question.getList_answer().listIterator();
        while(li.hasNext()){
            CheckBox cb = new CheckBox(this);
            Answer answer = li.next();
            cb.setTextSize(15);
    	    cb.setTypeface(Typeface.DEFAULT_BOLD);
            cb.setText(answer.getText());
            final int code = answer.getCode();
            cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
    			public void onCheckedChanged(CompoundButton buttonView,
    					boolean isChecked) {
    				if(isChecked){
    					response.setAnswer(code);
    				} else {
    					response.deleteAnswer(code);
    				}
    			}
    		});
            ll.addView(cb);   
        }
        return ll;
    }
    
    public static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8*1024);
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
    
    /*
     * Send answer to server
     * */
    private void sendResponse() {
   		response.setComment(comment.getText().toString());
   		AnswerServer as = LibreGeoSocial.getInstance().sendResponse(response);
   		
   		new AlertDialog.Builder(this)
        .setMessage(as.getMessage())
        .setCancelable(false)
        .setPositiveButton("Accept", new DialogInterface.OnClickListener() {
        	public void onClick(DialogInterface dialog, int id) {
                /* User clicked OK, no need to do anything */
        		defaultLayout();
        	}
        })
        .show();
    }
}
